let CODE = {
  SUCCESS: 200,
  PARAM_ERROR: 10001,//参数错误
  USER_ACCOUNT_ERROR: 20001,//账号密码错误
  USER_LOGIN_ERROR: 30001,//用户未登录
  BUSINESS_ERROR: 40001,//业务请求失败
  AUTH_ERROR: 50001//认证失败或token过期
}
var jwt = require('jsonwebtoken') //引入token

module.exports = {
  pager({ currentPage, pageSize }) {
    let currentpage = parseInt(currentPage)
    let pagesize = parseInt(pageSize)
    console.log('1111222', currentpage, typeof pagesize);
    const skipIndex = (currentpage - 1) * pagesize
    return {
      page: { currentpage, pagesize }, skipIndex
    }
  },
  TreeMenuList(data) {
    let result = []; // 返回的树形数据
    let map = {};    // 存储id到节点的映射

    // 首先为每个节点初始化children数组，并构建映射
    data.forEach(item => {
      // 复制原对象并初始化children，避免修改原数据
      map[item._id] = { ...item, children: [] };
    });

    // 然后构建树形结构
    data.forEach(item => {
      const currentNode = map[item._id];
      const parentId = item.parentId;

      if (parentId) {
        // 检查父节点是否存在于映射中
        if (map[parentId]) {
          map[parentId].children.push(currentNode);
        } else {
          // 处理父节点不存在的情况，作为根节点处理
          result.push(currentNode);
        }
      } else {
        // 没有parentId的作为根节点
        result.push(currentNode);
      }
    });

    return result;
  },
  success(data = '', msg = 'ok', code = CODE.SUCCESS) {
    return {
      data,
      msg,
      code
    }
  },
  fail(data = '', msg = 'ok', code = CODE.PARAM_ERROR) {
    return {
      data,
      msg,
      code
    }
  },
  decoded(Authorization) {
    if (Authorization) {
      let token = Authorization.split(' ')[1]
      return jwt.verify(token, 'lee')
    }
  },
  //时间格式化函数
  formateDate(date, rule) {
    let fmt = rule || 'yyyy-MM-dd hh:mm:ss'
    if (/(y+)/.test(fmt)) {
      fmt = fmt.replace(RegExp.$1, date.getFullYear())
    }
    const o = {
      // 'y+': date.getFullYear(),
      'M+': date.getMonth() + 1,
      'd+': date.getDate(),
      'h+': date.getHours(),
      'm+': date.getMinutes(),
      's+': date.getSeconds()
    }
    for (let k in o) {
      if (new RegExp(`(${k})`).test(fmt)) {
        const val = o[k] + '';
        fmt = fmt.replace(RegExp.$1, RegExp.$1.length == 1 ? val : ('00' + val).substr(val.length));
      }
    }
    return fmt;
  },
}